package com.wm.wmim.server.handler;

import com.wm.wmim.common.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author weiming
 * @date 2025/2/13 17:23
 * @description
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.wm.wmim")
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 排除已返回ResponseEntity或特定注解的方法
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> converterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 统一封装
        if (body instanceof Result) {
            Integer httpStatus = ((Result<?>) body).getHttpStatus();
            if (httpStatus != null){
                response.setStatusCode(HttpStatus.resolve(httpStatus));
            }
        } else {
            body = Result.success(body);
        }
        return body;
    }
}

